package cn.wolfcode.redis.service.impl;

import cn.wolfcode.domain.User;
import cn.wolfcode.redis.service.IUserRedisService;
import cn.wolfcode.redis.utils.RedisKey;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserRedisServiceImpl implements IUserRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public String setToken(User userInfo) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKey.USER_LOGIN_TOKEN.join(token);
        String user = JSON.toJSONString(userInfo);
        template.opsForValue().set(key, user, RedisKey.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    @Override
    public User getUserByToken(String token) {
        // 对token参数进行判空
        if (!StringUtils.hasText(token)) {
            return null;
        }
        //通过token去redis中查询
        String key = RedisKey.USER_LOGIN_TOKEN.join(token);
        if (template.hasKey(key)) {
            // 得到的是一个Json类型的字符串
            String userStr = template.opsForValue().get(key);
            // 需要把此字符串转换成Java中的UserInfo对象
            User user = JSON.parseObject(userStr, User.class);
            // 把redis中的token有效时间重置为30分钟
            template.expire(key, RedisKey.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return user;
        }
        return null;
    }
}
